﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using Microsoft.VisualBasic.FileIO;
using MvcApplication1.CsvParser;
using WebService.Models;

namespace WebService.Controllers
{
    public class DataController : ApiController
    {
        const string url = "http://earthquake.usgs.gov/earthquakes/catalogs/eqs7day-M2.5.txt";

        // GET /api/data
        public async Task<IEnumerable<EarthquakeRecord>> Get()
        {
            var client = new HttpClient();
            var stream = await client.GetStreamAsync(url);

			var parser = new CsvFile(stream);
			parser.Delimiters = new string[] { "," };

			var dti = new DateTimeFormatInfo();
			dti.LongDatePattern = "dddd, MMMM d, HH:mm:ss K";

			return from fields in parser.Parse().Skip(1)
					  select new EarthquakeRecord
					  {
						  Src = fields[0],
						  Eqid = fields[1],
						  Version = fields[2],
						  Datetime = DateTime.Parse(fields[3].Replace("UTC", "+0"), dti),
						  Lat = Decimal.Parse(fields[4]),
						  Lon = Decimal.Parse(fields[5]),
						  Magnitude = Decimal.Parse(fields[6]),
						  Depth = Decimal.Parse(fields[7]),
						  NST = fields[8],
						  Region = fields[9]
					  };
			

			//var parser = new TextFieldParser(stream);
			//parser.TextFieldType = FieldType.Delimited;
			//parser.SetDelimiters(",");
			//parser.HasFieldsEnclosedInQuotes = true;

			//var result = new List<EarthquakeRecord>();
			//var fields = parser.ReadFields(); // first line contains field names... ignore it
			//while (!parser.EndOfData)
			//{
			//	fields = parser.ReadFields();

			//	result.Add(new EarthquakeRecord
			//	{
			//		Src = fields[0],
			//		Eqid = fields[1],
			//		Version = fields[2],
			//		Datetime = DateTime.Parse(fields[3].Replace("UTC", "+0"), dti),
			//		Lat = Decimal.Parse(fields[4]),
			//		Lon = Decimal.Parse(fields[5]),
			//		Magnitude = Decimal.Parse(fields[6]),
			//		Depth = Decimal.Parse(fields[7]),
			//		NST = fields[8],
			//		Region = fields[9]
			//	});
			//}

			//return result;
        }
    }
}